#! /bin/bash

create_dir(){
    #创建本地持久化目录
    mkdir -p service/{prometheus,grafana}/{config,data}
    mkdir -p service/prometheus/config/rules
    mkdir -p service/prometheus/data/prometheus
    # 授权，或者执行提示 Permission denied
    sudo chmod -R 777 ./service
}

update_pic_chart(){
    # 备份
    # mv ./service/grafana/data/plugins/grafana-piechart-panel{,.bat}
    # 下载
    wget -nv https://grafana.com/api/plugins/grafana-piechart-panel/versions/latest/download -O ./service/grafana/data/plugins/grafana-piechart-panel.zip
    # 更新
    unzip -qo ./service/grafana/data/plugins/grafana-piechart-panel.zip -d ./service/grafana/data/plugins/
    # mv /tmp/grafana-piechart-panel ./service/grafana/data/plugins/
}

start_service(){
    # 启动服务
    docker-compose up -d
    clear
    docker-compose ps
}

stop_server(){
    # 停止服务
    docker-compose down
}



# 启动函数
main(){
    docker-compose  ps | grep prometheus > /dev/null
    case $1 in
    "")
        if [ $? != 0 ]
        then
            create_dir
            start_service
        else
            echo "Confirm to stop the current service!  yes | no"
            read -p "> "  selet
            case $selet in
            y | yes)
                stop_server
                ;;
            n | no)
                exit 0
                ;;
            *)
                echo "请输入 yes | no "
                exit 1
                ;;
            esac
        fi
        ;;
    update)
        if [ $? != 0 ]
        then
            update_pic_chart
            start_service
        else
            update_pic_chart
            docker-compose down
            sleep 2
            start_service
        fi
        ;;
    *)
        echo "The only parameter is update"
        exit 1
        ;;
    esac


}

main $1